<?php
namespace Home\Controller;

class EntrustTraController extends HomeBaseController
{

    public function agentbuyingp()
    {
        if(session('uid')==null){
            $this->ajaxReturn(array('code'=>'error','info' => '请选去登录！'));
            exit();
        }
        $buy_type = I('is_loan',1);
        $category_id=I('category_id','');
        $price=I('price',0);
        $period=I('period','');
        $number=I('number',0);
        $term=I('term','');
        $duration=I('duration',0);
        $buyauthpwd=I("buyauthpwd",'');
        $buyauthpwd=md5($buyauthpwd);
        is_numeric($price);
        if(!preg_match('/^\\d+$/',$price) || $price<0) {
            $this->ajaxReturn(array('code'=>'error','info' => '买入单价金额输入错误'));
            exit();
        }
        
        is_numeric($number);
        if(!preg_match('/^\\d+$/',$number) || $number<0) {
            $this->ajaxReturn(array('code'=>'error','info' => '买入数量输入错误'));
            exit();
        }
        
        is_numeric($duration);
        if(!preg_match('/^\\d+$/',$duration)) {
            $this->ajaxReturn(array('code'=>'error','info'=>'有效期错误'));
            exit();
        }
        if($buyauthpwd==''){
            $this->ajaxReturn(array('code'=>'error','info' => '交易密码不能为空'));
            exit();
        }
        $DomainType=M('DomainType')->find($category_id);
        if(empty($DomainType)){
            $this->ajaxReturn(array('code'=>'error','info' => '此域名类型有误！'));
            exit();
        }
        if($buy_type==2 || $buy_type=='2'){
            if($period=='') {
                $this->ajaxReturn(array('code'=>'error','info' => '请选择贷款产品！'));
                exit();
            }
            $InvesDomcate = M('InvesDomcate')->field('inve_id,domtypeid,credit,rate')->find($period);
            if(empty($InvesDomcate)) {
                $this->ajaxReturn(array('code'=>'error','info' => '贷款产品不存在！'));
                exit();
            }
            $investinfo = M('InvestorInfo')->field('uid')->find($InvesDomcate['inve_id']);
            if(empty($investinfo)) {
                $this->ajaxReturn(array('code'=>'error','info' => '贷款产品不存在！'));
                exit();
            }
            if($category_id!=$InvesDomcate['domtypeid']) {
                $this->ajaxReturn(array('code'=>'error','info' => '您选择的贷款产品不支持此类型域名贷款'));
                exit();
            }
            if($price<$InvesDomcate['credit']) {
                $this->ajaxReturn(array('code'=>'error','info' =>'信用购买单价不能低于'.$InvesDomcate['credit']));
                exit();
            }
            $creditmoney=M('UserAssets')->field('creditmoney')->where('uid='.$investinfo['uid'])->select();
            $creditmoney=$creditmoney[0]['creditmoney'];
            if($creditmoney<($InvesDomcate['credit']*$number)){
                $this->ajaxReturn(array('code'=>'error','info' => '此项目理财宝金额不足请重新选择其他贷款产品'));
                exit();
            }
        }
        $user = M('User')->find(session('uid'));
        if($user['transpasswd']!=$buyauthpwd) {
            $this->ajaxReturn(array('code'=>'error','info' => '交易密码输入错误'));
            exit();
        }
        $trans_money=0;
        $byue=D('UserAssets')->field("avail_money,present_money,notpresent_money,locked_money")->where("uid=".session('uid'))->select();
        if($buy_type==2 || $buy_type=='2'){
            $guanlifei = M('TradeFee')->field('rate')->where('type=3')->select();
            $guanlifei=$guanlifei[0]['rate'];
            $trans_money=($price-$InvesDomcate['credit'])*$number;
        } else {
            $trans_money=$price*$number;
        }
        $canUsemoney=$byue[0]['present_money']+$byue[0]['notpresent_money'];
        if($canUsemoney<$trans_money){
            $this->ajaxReturn(array('code'=>'error','info' => '您的可用余额不足，请先充值'));
            exit();
        }
        
        $entr = M("UserEntrust");
        $data['trans_type']=1;
        $data['uid']=session('uid');
        $data['domain_typeid']=$category_id;
        $data['trans_mode']=$buy_type;
        $data['unit_price']=$price;
        $data['dnumber']=$number;
        $data['effect_time']=$duration;
        $data['surplus']=$number;
        if($buy_type==2 || $buy_type=='2'){
            $data['cred_code']=D('CredFlow')->create_uuid();
        }else{
            $data['cred_code']='';
        }
        if($buy_type==2){
            $data['credit']=$InvesDomcate['credit'];
        }
        if($duration!=0) {
          $data['expire_date']= date("Y-m-d",strtotime($duration." day")).' 00:00:00';
        }else {
          $data['expire_date']=date("Y-m-d",strtotime("780 day")).' 00:00:00';
        }
        $data['createdate']=date('y-m-d H:m:s',time());
        $id = $entr->add($data);
        
        
        
        if($buy_type==2 || $buy_type=='2'){
            $entrCred=M('EntrCred');
            $entrcrdate['rate']=$InvesDomcate['rate'];
            $entrcrdate['term']=$term;
            $entrcrdate['entr_id']=$id;
            $entrcrdate['credit']=$InvesDomcate['credit'];
            $entrcrdate['createdate']=date('y-m-d H:m:s',time());
            $entrCred->add($entrcrdate);
        }
        $byueavail_money=$byue[0]['avail_money'];
        $byuepresent_money=$byue[0]['present_money'];
        $byuenotpresent_money=$byue[0]['notpresent_money'];
        $tradeFe=M('TradeFee')->field('rate')->where('type=2')->select();
        if(empty($tradeFe)){
            $tradeFe=0;
        }else{
            $tradeFe=$tradeFe[0]['rate'];
        }
        $buycreflows='';
        $allcount=0;
        if ($id){
            $limitStart=0;
            while (true){
            $entrcond['trans_type']=2;
            $entrcond['domain_typeid']=$category_id;
            $entrcond['uid']=array('neq',session('uid'));
            $entrcond['unit_price']=array('elt',$price);
            $entrcond['expire_date']=array('egt',date("Y-m-d").' 00:00:00');
            $entrcond['surplus']=array('gt',0);
            $entrcond['status']=0;
            $seller = $entr->field('id,uid,unit_price,trans_mode,surplus,cred_code')
            ->where($entrcond)->order("unit_price asc,createdate asc")->limit($limitStart,1)->select();
            if(empty($seller) || $allcount==$number) {
                $dongjie=0;
                if($buy_type==2 || $buy_type=='2'){
                } else {
                    $dongjie=($number-$allcount)*$price;
                }
                M('UserAssets')->where('uid='.session('uid'))->setInc('locked_money',$dongjie);
                if($dongjie>=$byuenotpresent_money){
                    $byuepresent_money=$byuepresent_money-($dongjie-$byuenotpresent_money);
                    $byuenotpresent_money=0;
                }else{
                    $byuenotpresent_money=$byuenotpresent_money-$dongjie;
                }
                M('UserAssets')->where('uid='.session('uid'))->setField(array('avail_money'=>$byueavail_money));
                M('UserAssets')->where('uid='.session('uid'))->setField(array('present_money'=>$byuepresent_money));
                M('UserAssets')->where('uid='.session('uid'))->setField(array('notpresent_money'=>$byuenotpresent_money));
                if($allcount>0){
                    $this->ajaxReturn(array('code'=>'success','info' => '您已成功购买'.$allcount.'个'.$DomainType['name'].'域名！'));
                }else{
                    $this->ajaxReturn(array('code'=>'success','info' => '您的购买已提交！'));
                }
                exit();
            }
            
            
            $seller=$seller[0];
            if($buy_type==2 || $buy_type=='2'){
                if($seller['unit_price']<=$InvesDomcate['credit']){
                    $seller['unit_price']=$price;
                }
            }
            if($seller['trans_mode']==2){
                $moyDao=M();
                $domainList= M('CredflowDomian')->join(' as a left join dd_user_domains as b on a.domainid=b.id')->field('a.domainid as id,b.domain')->where("a.cred_code='".$seller['cred_code']."'")->select();
                $huankuan=0;
                if(count($domainList)==0){
                    $limitStart=$limitStart+1;
                    continue;
                }
                if(($number-$allcount)<count($domainList)){
                    $limitStart=$limitStart+1;
                    continue;
                }
                $consellnum=count($domainList);
                $creflowarr= M('CredFlow')->field('id,investuid,money,persionnum,rpersionum,interest,penalty,mangrate')->where("cred_code='".$seller['cred_code']."' and status in (1,3) and loanduid=".$seller['uid'])->select();
                foreach ($creflowarr as $flow){
                    $huankuan+=$flow['money']+($flow['interest']*($flow['persionnum']-$flow['rpersionum']))+$flow['penalty']+$flow['mangrate'];
                }
                if($huankuan>($consellnum*$seller['unit_price'])){
                    $limitStart=$limitStart+1;
                    continue;
                }
                
                foreach ($creflowarr as $floarr){
                    M('CredFlow')->where('id='.$floarr['id'])->setField(array('status'=>2,'rpersionum'=>$floarr['persionnum']));
                    M('RepaymentFlow')->where("cred_code='".$seller['cred_code']."'")->setField(array('is_yq'=>3));
                    $touzimoney=$floarr['money']+($floarr['interest']*($floarr['persionnum']-$floarr['rpersionum']))+$floarr['penalty'];
                    M('UserAssets')->where('uid='.$floarr['investuid'])->setInc('avail_money',$touzimoney);
                    M('UserAssets')->where('uid='.$floarr['investuid'])->setInc('present_money',$touzimoney);
                    
                    $capDetail=M('UserCaptdetail');
                    $datcap['uid']=$floarr['investuid'];
                    $datcap['tran_income']=5;
                    $datcap['flow_money']=$touzimoney;
                    $datcap['tran_type']=1;
                    $datcap['createdate']=date('y-m-d H:m:s',time());
                    $datcap['userremark']='抵押域名放贷还款收入';
                    $capDetail->add($datcap);
                }
                M('LoaderInfo')->where("cred_code='".$seller['cred_code']."'")->setField(array('status'=>4));
                foreach ($domainList as $dom){
                    M('UserDomains')->where('id='.$dom['id'])->setField(array('is_mortage'=>1));
                }
            }else{
                if($seller['surplus']<=($number-$allcount)){
                    $consellnum=$seller['surplus'];
                }else{
                    $consellnum=($number-$allcount);
                }
                $domainList = M('UserDomains')->field('id,domain')->
                where('uid='.$seller['uid'].' and trans_status=2 and is_mortage=1 and domain_typeid='.$category_id)->limit($consellnum)->select();
            }
            $mony=$consellnum*$seller['unit_price'];
            $sellsxf=0;
            if($tradeFe>0){
                $sellsxf=$mony*($tradeFe*0.01);
              
                $platPrflog=M('PlatformProfitlog');
                $platlog['money']=$sellsxf;
                $platlog['comefr']=1;
                $platlog['userid']=$seller['uid'];
                $platlog['descr']='ID为'.$seller['uid'].'的用户卖出域名，平台收入手续费:'.$sellsxf;
                $platlog['createdate']=date('y-m-d H:m:s',time());
                $platPrflog->data($platlog)->add();
            }
            
            
            $domainTranslog = M("DomainTranslog");
            $tralog['buyerid']=session('uid');
            $tralog['sellerid']=$seller['uid'];
            $tralog['trans_number']=$consellnum;
            $tralog['price']=$seller['unit_price'];
            $tralog['totel_price']=$consellnum*$seller['unit_price'];
            $tralog['trans_fee']=$sellsxf;
            $tralog['actual_price']=$tralog['totel_price']-$sellsxf;
            $tralog['domain_type_id']=$category_id;
            $tralog['createdate']=date('y-m-d H:m:s',time());
            $logid=$domainTranslog->data($tralog)->add();
           
            $faxiseller=0;
            if($buy_type==2 || $buy_type=='2'){
                $credflowid=D('CredFlow')->loan(session('uid'),$investinfo['uid'],$InvesDomcate['credit']*$consellnum,$category_id,$InvesDomcate['inve_id'],$term,$InvesDomcate['rate'],$domainList,$InvesDomcate['credit'],$guanlifei,$data['cred_code']);
            }
            foreach ($domainList as $dom){
                $dTradetail=M('DomainTransdetail');
                $dtradet['buyerid']=session('uid');
                $dtradet['sellerid']=$seller['uid'];
                $dtradet['logid']=$logid;
                $dtradet['price']=$seller['unit_price'];
                $dtradet['domain']=$dom['domain'];
                $dtradet['domain_id']=$dom['id'];
                $dtradet['domain_type_id']=$category_id;
                $dtradet['creatdate']=date('y-m-d H:m:s',time());
                $dTradetail->data($dtradet)->add();
                 M('UserDomains')->where('id='.$dom['id'])->setField(array('price'=>$seller['unit_price'],'trans_status'=>1,'is_mortage'=>$buy_type,'uid'=>session('uid'),'come'=>1));
            }
            
            if($seller['trans_mode']==1){
                $mony=sprintf("%.2f", $mony-$sellsxf);
            }else {
                $mony=sprintf("%.2f", $mony-$sellsxf-$huankuan);
            }
            M('UserAssets')->where('uid='.$seller['uid'])->setInc('present_money',$mony);
            M('UserAssets')->where('uid='.$seller['uid'])->setInc('avail_money',$mony);
            if($buy_type==2 || $buy_type=='2'){
                $trans_money=($seller['unit_price']-$InvesDomcate['credit'])*$consellnum;
            } else {
                $trans_money=($seller['unit_price'])*$consellnum;
            }
            $byueavail_money=$byueavail_money-$trans_money;
            
            if($byuenotpresent_money<$trans_money){
                $byuepresent_money=$byuepresent_money-($trans_money-$byuenotpresent_money);
                $byuenotpresent_money=0;
            }else{
                $byuenotpresent_money=$byuenotpresent_money-$trans_money;
            }
                
            /**
             * 资金交易明细  卖方
             * @var unknown
             */
            $userremark="您以单价".$seller['unit_price'].'卖出'.$consellnum.'个域名,收入'.$mony.'扣除手续费:'.$sellsxf;
            if($seller['trans_mode']==2){
                $userremark=$userremark.',扣除抵押域名一次还清:'.$huankuan."元本金和利息";
            }
            $array = array( "uid" => $seller['uid'], "tran_income" => 4,"flow_money"=>$mony,"tran_type"=>1,
                "createdate"=>date('y-m-d H:m:s',time()),"userremark"=>$userremark);
            D('UserCaptdetail')->inser($array);
            
            /**
             * 资金交易明细 买方
             */
            $userremark="您以单价".$seller['unit_price'].'买入'.$consellnum.'个域名,交易价格:'.$trans_money;
            if($buy_type==2 || $buy_type=='2'){
                $userremark=$userremark.',其中抵押授信总额度:'.($InvesDomcate['credit']*$consellnum);
            }
            $userremark=$userremark.',实际支付金额:'.$trans_money;
            $array = array( "uid" => session('uid'), "tran_income" => 4,"flow_money"=>$trans_money,"tran_type"=>2,
                "createdate"=>date('y-m-d H:m:s',time()),"userremark"=>$userremark);
            D('UserCaptdetail')->inser($array);
            
            $sellersurplus=0;
            $mallsurplus=0;
            $sellstatus=0;
            $mallstatus=0;
            if($seller['surplus']<($number-$allcount)){
                $mallsurplus=($number-$allcount)-$seller['surplus'];
                $sellstatus=1;
            }else if($seller['surplus']>($number-$allcount)){
                $sellersurplus=$seller['surplus']-($number-$allcount);
                $mallstatus=1;
            }else {
                $sellstatus=1;
                $mallstatus=1;
            }
            M('UserEntrust')->where('id='.$seller['id'])->setInc('trans_money',$mony);
            M('UserEntrust')->where('id='.$seller['id'])->setField(array('surplus'=>$sellersurplus,'status'=>$sellstatus));
            M('UserEntrust')->where('id='.$id)->setInc('trans_money',$trans_money);
            M('UserEntrust')->where('id='.$id)->setField(array('surplus'=>$mallsurplus,'status'=>$mallstatus,'cred_code'=>$data['cred_code']));
            $allcount+=$consellnum;
                }
            }
            if($number>$allcount){
                $dongjie=0;
                if($buy_type==1 || $buy_type=='1'){
                    $dongjie=($number-$allcount)*$price;
                    M('UserAssets')->where('uid='.session('uid'))->setInc('locked_money',$dongjie);
                }
                if($dongjie>=$byuenotpresent_money){
                    $byuepresent_money=$byuepresent_money-($dongjie-$byuenotpresent_money);
                    $byuenotpresent_money=0;
                }else{
                    $byuenotpresent_money=$byuenotpresent_money-$dongjie;
                }
                $byueavail_money=$byueavail_money-$dongjie;
                M('UserAssets')->where('uid='.session('uid'))->setField(array('avail_money'=>$byueavail_money));
                M('UserAssets')->where('uid='.session('uid'))->setField(array('present_money'=>$byuepresent_money));
                M('UserAssets')->where('uid='.session('uid'))->setField(array('notpresent_money'=>$byuenotpresent_money));
                $this->ajaxReturn(array('code'=>'success','info' => '您已成功购买'.$allcount.'个'.$DomainType['name'].'域名！'));
                exit();
            }
   }

    /**
     * 委托卖域名
     */
    public function fetchtradable()
    {
        if(session('uid')==null){
            $this->ajaxReturn(array('code'=>'error','info' => '请选去登录！'));//0错误，1成功
            exit();
        }
        $seller_type = I('is_loan',1);// 1=卖出正常的域名，2=卖出抵押中的域名
        $category_id=I('category_id','');//域名类型
        $cred_code=I('cred_code',0);//抵押中的借款唯一标识码
        $price=I('price',0);
        $number=I('number',0);
        $duration=I('duration',0);//有效期
        $buyauthpwd=I("authpwd",'');//交易密码
        $buyauthpwd=md5($buyauthpwd);
        /**
         * 校验合法性 begin
        */
        is_numeric($price);
        if(!preg_match('/^\\d+$/',$price)) {
            $this->ajaxReturn(array('code'=>'error','info' => '卖出单价金额输入错误'));//0错误，1成功
            exit();
        }
        
        is_numeric($number);
        if(!preg_match('/^\\d+$/',$number)) {
            $this->ajaxReturn(array('code'=>'error','info' => '卖出入数量输入错误'));//0错误，1成功
            exit();
        }
        if(($seller_type==1||$seller_type=='1') && $number<1) {
            $this->ajaxReturn(array('code'=>'error','info' => '卖出入数量输入错误'));//0错误，1成功
            exit();
        }
        is_numeric($duration);
        if(!preg_match('/^\\d+$/',$duration)) {
            $this->ajaxReturn(array('code'=>'error','info' => '有效期错误'));//0错误，1成功
            exit();
        }
        if($buyauthpwd==''){
            $this->ajaxReturn(array('code'=>'error','info' => '交易密码不能为空'));//0错误，1成功
            exit();
        }
        $user = M('User')->find(session('uid'));
        if($user['transpasswd']!=$buyauthpwd) {
            $this->ajaxReturn(array('code'=>'error','info' => '交易密码输入错误'));//0错误，1成功
            exit();
        }
        $idcond['id']=$category_id;
        $credit_limit = M('DomainType')->field('name')->where($idcond)->select();
        $credit=0;
        $huankuan=0;
        if($seller_type==2 || $seller_type=='2'){//卖出抵押中的域名
            $allcredprice=$price;
            $creflowarr= M('CredFlow')->field('id,investuid,money,persionnum,rpersionum,interest,penalty,mangrate')->where("is_entrust=0 and cred_code='".$cred_code."' and status in (1,3) and loanduid=".session('uid'))->select();
            if(empty($creflowarr)){
                $this->ajaxReturn(array('code'=>'error','info' => '抵押产品不存在'));//0错误，1成功
                exit();
            }
            $domanList=M('CredflowDomian')->join(' as a left join dd_user_domains b on a.domainid=b.id')->field('b.id as id,a.credit,b.domain')->where("a.cred_code='".$cred_code."'")->select();
            if(count($domanList)==0){
                $this->ajaxReturn(array('code'=>'error','info' => '卖出的抵押域名不存在'));//0错误，1成功
                exit();
            }
        
            $credit =$domanList[0]['credit'];
            foreach ($creflowarr as $flow){
                $huankuan+=$flow['money']+($flow['interest']*($flow['persionnum']-$flow['rpersionum']))+$flow['penalty']+$flow['mangrate'];
            }
            if($allcredprice<$huankuan){
                $this->ajaxReturn(array('code'=>'error','info' => "您卖出的总金额不能低于".$huankuan.'元'));//0错误，1成功
                exit();
            }
            $number=count($domanList);
            //平均单价
            $price=$allcredprice/$number;
        }
        $sellDao = M('UserDomains');
        if($seller_type==1){//未抵押
            $sellDomCond['is_mortage']=1;
            $sellDomCond['uid']=session('uid');
            $sellDomCond['domain_typeid']=$category_id;
            $sellDomCond['trans_status']=1;
            $sellDomCond['check_status']=3;
            $sellCount=$sellDao->where($sellDomCond)->count();
            if($sellCount<$number){//验证卖家是否有这么多域名可以卖出
                $this->ajaxReturn(array('code'=>'error','info' => "您可卖出域名实际数量为".$sellCount.',小于当前卖出数'));//0错误，1成功
                exit();
            }
        }
       
        
        /**
         * 插入域名批量卖出委托表
         */
        $entr = M("UserEntrust");
        $data['trans_type']=2;
        $data['uid']=session('uid');
        $data['domain_typeid']=$category_id;
        $data['trans_mode']=$seller_type;
        $data['unit_price']=$price;
        $data['dnumber']=$number;
        $data['effect_time']=$duration;
        $data['surplus']=$number;
        $data['credit']=$credit;
        if($seller_type==2 || $seller_type=='2'){
            $data['cred_code']=$cred_code;
        }else{
            $data['cred_code']='';
        }
        if($duration!=0) {
            $data['expire_date']= date("Y-m-d",strtotime($duration." day")).' 00:00:00';
        }else {
            $data['expire_date']=date("Y-m-d",strtotime("780 day")).' 00:00:00';
        }
        $data['createdate']=date('y-m-d H:m:s',time());
        $id = $entr->add($data);
        if($seller_type==2 || $seller_type=='2'){
            M('CredFlow')->where("is_entrust=0 and cred_code='".$cred_code."' and status in (1,3) and loanduid=".session('uid'))->setField(array('is_entrust'=>$id));
        }
        $trans_money=0;
        $tradeFe=M('TradeFee')->field('rate')->where('type=2')->select();
        if(empty($tradeFe)){
            $tradeFe=0;
        }else{
            $tradeFe=$tradeFe[0]['rate'];
        }
        
        $guanlifei = M('TradeFee')->field('rate')->where('type=3')->select();
        $guanlifei=$guanlifei[0]['rate'];
        
        /**
         * 校验合法性 end
         */
        $allcount=0;
        if ($id){
            $limitStart=0;
            while (true){
                if($allcount==$number){
                    break;//已经全部交易完成
                } else {
            /**
             * 查询与之相匹配的买家委托
             *
             */
            $entrcond['trans_type']=1;
            $entrcond['domain_typeid']=$category_id;
            $entrcond['unit_price']=array('egt',$price);//只卖出大余等于的价格
            $entrcond['expire_date']=array('egt',date("Y-m-d").' 00:00:00');
            $entrcond['status']=0;
            $entrcond['uid']=array('neq',session('uid'));
            if($seller_type==2 || $seller_type=='2'){
                $entrcond['surplus']=array('egt',count($domanList));//必须大于等于抵押卖出的域名数，不然没法处理卖家还款信息
            }else{
                $entrcond['surplus']=array('gt',0);//剩余大于0
            }
            $buyer = $entr->field('id,uid,unit_price,trans_mode,surplus,credit,cred_code')->
            where($entrcond)->order("unit_price desc,createdate asc")->limit($limitStart,1)->select();
            if(empty($buyer)) {//若没有满足条件的买入则直接返回
                if($seller_type==2 || $seller_type=='2'){
                    foreach ($domanList as $dom){
                        M('UserDomains')->where('id='.$dom['id'])->setField(array('trans_status'=>2));
                    }
                    $this->ajaxReturn(array('code'=>'success','info' => '您的委托卖出已提交！'));//0错误，1成功
                    exit();
                }else{
                    $litnum=$number-$allcount;
                    $updcond=" UPDATE dd_user_domains SET trans_status = 2 where uid=".session('uid')." AND domain_typeid=".$category_id." AND is_mortage=1 AND trans_status=1 AND check_status=3 order BY createdate LIMIT ".$litnum;
                    $Upao = M();
                    $upnum = $Upao->execute($updcond);
                    if($allcount>0){
                        $this->ajaxReturn(array('code'=>'success','info' => '您已成功卖出'.$allcount.'个'.$credit_limit[0]['name'].'域名！'));//0错误，1成功
                    } else {
                        $this->ajaxReturn(array('code'=>'success','info' => '您的委托卖出已提交！'));//0错误，1成功
                    }
                }
            }
            $value=$buyer[0];
            //抵押卖出，必须先看卖出的收益是否可以还清抵押
            if($seller_type==2 || $seller_type=='2'){
                $credSellerAllmoney=$value['unit_price']*$number;
                if($credSellerAllmoney<$allcredprice){
                    $limitStart=$limitStart+1;
                    continue;
                }
            }
            $consellnum=0;//实际交易数量
            if($value['surplus']>($number-$allcount)){//买家剩余数量大于等于卖出域名数
                $consellnum=($number-$allcount);
            }else if($value['surplus']<($number-$allcount)){
                $consellnum=$value['surplus'];
            } else {
                $consellnum=($number-$allcount);
            }
            if($value['trans_mode']==2){//去投资标里匹配一个贷款产品，若找不到，则跳过
                $entrcred=M('EntrCred')->where('entr_id='.$value['id'])->select();
                $entrcred=$entrcred[0];
                $entrcondi['dd_inves_domcate.domtypeid']=$category_id;
                $entrcondi['dd_inves_domcate.rate']=array('elt',$entrcred['rate']);
                $entrcondi['dd_investor_info.term_begin']=array('elt',$entrcred['term']);
                $entrcondi['dd_investor_info.term_end']=array('egt',$entrcred['term']);
                $entrcondi['dd_user_assets.creditmoney']=array('egt',$entrcred['credit']*$consellnum);
                $dao=M('InvesDomcate');
                $entrcredlist=$dao->join('LEFT JOIN  dd_investor_info ON dd_inves_domcate.inve_id=dd_investor_info.id')->
                join("LEFT JOIN dd_user_assets ON dd_investor_info.uid=dd_user_assets.uid")->
                field("dd_investor_info.id,dd_investor_info.uid,dd_inves_domcate.rate,dd_inves_domcate.credit,dd_user_assets.creditmoney")
                ->where($entrcondi)->order('dd_inves_domcate.rate')->select();
                if(empty($entrcredlist) || count($entrcredlist)==0){
                    $limitStart=$limitStart+1;
                    continue;
                }else{
                    $inverInfo=$entrcredlist[0];
                }
            }
            $buyUnitprice=$value['unit_price'];//顺序不能反了
            $buyAsset=D('UserAssets')->field("avail_money,notpresent_money,present_money,locked_money")->where("uid=".$value['uid'])->select();//获得买方当前余额
            $mony=$value['unit_price']*$consellnum;//最终卖家实际交易价格
            if($seller_type==1){//未抵押
                $domanList=M('UserDomains')->field('id,domain')->where($sellDomCond)->order("createdate")->limit($consellnum)->select();
            }
            
            $sellsxf=0;//卖方承担的手续费
            //插入平台手续费收入log
            if($tradeFe>0){
                $sellsxf=$mony*$tradeFe;
                $platPrflog=M('PlatformProfitlog');
                $platlog['money']=$sellsxf;
                $platlog['comefr']=1;//来源,1=手续费，2=利息，3=罚息
                $platlog['userid']=session('uid');
                $platlog['descr']='ID为'.session('uid').'的用户卖出域名，平台收入手续费:'.$sellsxf;
                $platlog['createdate']=date('y-m-d H:m:s',time());
                $platPrflog->data($platlog)->add();
            }
            
            //插入交易记录
            $domainTranslog = M("DomainTranslog");
            $tralog['buyerid']=$value['uid'];
            $tralog['sellerid']=session('uid');
            $tralog['trans_number']=$consellnum;
            $tralog['price']=$value['unit_price'];
            $tralog['totel_price']=$consellnum*$value['unit_price'];
            $tralog['trans_fee']=$sellsxf;
            $tralog['actual_price']=$tralog['totel_price']-$sellsxf;
            $tralog['domain_type_id']=$category_id;
            $tralog['createdate']=date('y-m-d H:m:s',time());
            $logid=$domainTranslog->data($tralog)->add();
            
            
            if($seller_type==2 || $seller_type=='2'){//卖家需要还清所有借款
                foreach ($creflowarr as $floarr){
                    M('CredFlow')->where('id='.$floarr['id'])->setField(array('status'=>2,'rpersionum'=>$floarr['persionnum']));
                    M('RepaymentFlow')->where("cred_code='".$cred_code."'")->setField(array('is_yq'=>3));
                    $touzimoney=$floarr['money']+($floarr['interest']*($floarr['persionnum']-$floarr['rpersionum']))+$floarr['penalty'];
                    M('UserAssets')->where('uid='.$floarr['investuid'])->setInc('avail_money',$touzimoney);
                    M('UserAssets')->where('uid='.$floarr['investuid'])->setInc('present_money',$touzimoney);
                    $array = array( "uid" => $floarr['investuid'], "tran_income" => 5,"flow_money"=>$touzimoney,"tran_type"=>2,"createdate"=>date('y-m-d H:m:s',time()),"userremark"=>'抵押域名放贷还款收入');
                    D('UserCaptdetail')->inser($array);
                }
                M('LoaderInfo')->where("cred_code='".$cred_code."'")->setField(array('status'=>4));
                
            }
            $faxiseller=0;
            foreach ($domanList as $dom){
                //域名交易记录明细
                $dTradetail=M('DomainTransdetail');
                $dtradet['buyerid']=$value['uid'];
                $dtradet['sellerid']=session('uid');
                $dtradet['logid']=$logid;
                $dtradet['price']=$value['unit_price'];
                $dtradet['domain']=$dom['domain'];
                $dtradet['domain_id']=$dom['id'];
                $dtradet['domain_type_id']=$category_id;
                $dtradet['creatdate']=date('y-m-d H:m:s',time());
                $dTradetail->data($dtradet)->add();
                //修改域名归属人为买家
                M('UserDomains')->where('id='.$dom['id'])->setField(array('price'=>$value['unit_price'],'trans_status'=>1,'is_mortage'=>$value['trans_mode'],'uid'=>$value['uid'],'come'=>1));
            }
            
            if($value['trans_mode']==2){//抵押购买-插入一条买方抵押记录
                $buyCredCode=D('CredFlow')->create_uuid();
                D('CredFlow')->loan($value['uid'],$inverInfo['uid'],$inverInfo['credit']*$consellnum,$category_id,$inverInfo['id'],$entrcred['term'],$inverInfo['rate'],$domanList,$inverInfo['credit'],$guanlifei,$buyCredCode);
            }
            if($seller_type==1){//未抵押卖出状态
                $mony=sprintf("%.2f", ($mony-$sellsxf));//卖方实际获得的金额
            }else {//抵押状态中交易（卖家收获的金额为：买家交易金额-手续费-利息-授信额度*交易数量）
                $mony=sprintf("%.2f", ($mony-$sellsxf-$huankuan));
            }
            //卖方账户变化
            M('UserAssets')->where('uid='.session('uid'))->setInc('present_money',$mony);
            M('UserAssets')->where('uid='.session('uid'))->setInc('avail_money',$mony);
        
            /**
             * 资金交易明细 卖方
             *
             */
            $userremark="您以单价".$value['unit_price'].'卖出'.$consellnum.'个域名,收入'.$mony.'扣除手续费:'.$sellsxf;
            if($seller_type==1){
                $userremark=$userremark.',扣除抵押本金及利息:'.$huankuan;
            }
            $array = array( "uid" => session('uid'), "tran_income" => 4,"flow_money"=>$mony,"tran_type"=>2,"createdate"=>date('y-m-d H:m:s',time()),"userremark"=>$userremark);
            D('UserCaptdetail')->inser($array);
            
            /**
             * 资金交易明细  买方
             * @var unknown
            */
            
            $mallmoney=0;
            $tuihuandongjie=0;
            if($value['trans_mode']==2){//抵押购买的
                $mallmoney=($value['unit_price']-$inverInfo['credit'])*$consellnum;
                M('UserAssets')->where('uid='.$value['uid'])->setDec('avail_money',$mallmoney);
                if($buyAsset['present_money']<$mallmoney){
                    M('UserAssets')->where('uid='.$value['uid'])->setField(array('present_money'=>0));
                    M('UserAssets')->where('uid='.$value['uid'])->setDec('notpresent_money',$mallmoney-$buyAsset['present_money']);
                }else{
                    M('UserAssets')->where('uid='.$value['uid'])->setDec('present_money',$mallmoney);
                }
            }else{//非抵押购买，需要处理锁定资金
                $mallmoney=$value['unit_price']*$consellnum;
                $tuihuandongjie=($buyUnitprice-$value['unit_price'])*$consellnum;
                M('UserAssets')->where('uid='.$value['uid'])->setDec('locked_money',($buyUnitprice*$consellnum));//去掉冻结的资金用于支付购买
                M('UserAssets')->where('uid='.$value['uid'])->setDec('avail_money',$mallmoney);
                M('UserAssets')->where('uid='.$value['uid'])->setInc('present_money',$tuihuandongjie);
            }
            
            $userremark="您实际支付了".$mallmoney."元购买域名";
            $array = array( "uid" => session('uid'), "tran_income" => 4,"flow_money"=>$mony,"tran_type"=>1,"createdate"=>date('y-m-d H:m:s',time()),"userremark"=>$userremark);
            D('UserCaptdetail')->inser($array);
        
            $sellersurplus=($number-$allcount);
            $mallsurplus=0;
            $sellstatus=0;
            $mallstatus=0;
            if($value['surplus']<($number-$allcount)){//买方实际可以买的数量小于卖方的
                $sellersurplus=($number-$allcount)-$value['surplus'];
                $mallstatus=1;
            }else if($value['surplus']>($number-$allcount)){
                $sellstatus=1;
                $mallsurplus=$value['surplus']-($number-$allcount);
            }else {
                $sellstatus=1;
                $mallstatus=1;
                $sellersurplus=0;
            }
           
            //修改卖方委托卖出记录
            M('UserEntrust')->where('id='.$id)->setInc('trans_money',$mony);
            M('UserEntrust')->where('id='.$id)->setField(array('surplus'=>$sellersurplus,'status'=>$sellstatus));
            //修改买方委托信息            
            M('UserEntrust')->where('id='.$value['id'])->setInc('trans_money',$mallmoney);
            M('UserEntrust')->where('id='.$value['id'])->setField(array('surplus'=>$mallsurplus,'status'=>$mallstatus));
            
            M("DomainType")->where('id='.$category_id)->setField(array('old_price'=>$value['unit_price']));
            $allcount+=$consellnum;//累加每次循环的价格
            if($number==$allcount){//这一步不能shao
                M('UserEntrust')->where('id='.$id)->setField(array('surplus'=>0,'status'=>1));
            }
                }
            }
            //记录平台账户资金收益记录
            $this->ajaxReturn(array('code'=>'success','info' => '您已成功卖出'.$allcount.'个'.$credit_limit[0]['name'].'域名！'));//0错误，1成功
        }
    }
    
}